module.exports = function (app) {
    return new handler(app);
};

var handler = function (app) {
    this.app = app;
};

var pro = handler.prototype;

pro.register = function (msg, session, next) {
    var that = this;

    var account = msg.account;
    var password = msg.password;
    var name = msg.name;
    var sex = msg.sex;

    console.log("authHandler.register: account is %s, password is %s, name is %s, sex is %s.", account, password, name, sex);

    var db = that.app.get("dbclient");
    var sql = "select * from user where account = ?";
    var sqlArgs = [account];

    db.query(sql, sqlArgs, function (err1, res1) {
        if (err1) {
            console.log("authHandler.register: query1 err: %s.", err1.message);
            next(null, { code: 500, error: true, reason: "server error." });
        } else if (res1.length > 0) {
            next(null, { code: 500, error: true, reason: "user exists." });
        } else {
            sql = "insert into user (account,password,name,sex,logintime,createtime) values(?,?,?,?,?,?)";
            var timestamp = Date.parse(new Date());
            sqlArgs = [account, password, name, sex, timestamp, timestamp];
            db.query(sql, sqlArgs, function (err2, res2) {
                if (err2) {
                    console.log("authHandler.register: query2 err: %s.", err2.message);
                    next(null, { code: 500, error: true, reason: "server error." });
                } else {
                    session.bind(account);
                    session.set("name", name);
                    session.set("sex", sex);
                    session.pushAll(function (err) {
                        if (err) console.log("authHandler.register: session.pushAll err: %s.", err);
                    });
                    next(null, { code: 200 });
                }
            });
        }
    });
};

pro.login = function (msg, session, next) {
    var that = this;

    var account = msg.account;
    var password = msg.password;

    console.log("authHandler.login: account is %s, password is %s.", account, password);

    var db = that.app.get("dbclient");
    var sql = "select * from user where account = ? and password = ?";
    var sqlArgs = [account, password];

    db.query(sql, sqlArgs, function (err1, res1) {
        if (err1) {
            console.log("authHandler.login: query1 err: %s.", err1.message);
            next(null, { code: 500, error: true, reason: "server error." });
        } else if (res1.length == 0) {
            next(null, { code: 501, error: true, reason: "user doesn't exists." });
        } else {
            next(null, { code: 200 });
        }
    });
};

pro.logout = function () {

};
